package org.rcy.ruicingmarket.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.rcy.framework.api.entity.ResultMessage;
import org.rcy.ruicingmarket.exception.OssException;
import org.rcy.ruicingmarket.view.ViewResourceVo;
import org.rcy.ruicingmarket.oss.view.ViewService;
import org.rcy.ruicingmarket.view.ViewVo;
import org.rcy.ruicingmarket.resource.ApiGroup;
import org.rcy.ruicingmarket.security.PrivilegeCheck;
import org.rcy.ruicingmarket.common.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/11 18:04
 */
@RestController
@Tag(name = "ossview", description = "后台视图控制器")
@RequestMapping("/view")
public class OssViewController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${oss.token.encryptkey}")
	private String tokenKey;

	@Autowired
	private ViewService viewService;

	@GetMapping("/getViewByUser")
	@PrivilegeCheck(group = ApiGroup.SYSTEM,name = "获取用户菜单资源",auth = true)
	@Parameter(name = "ossInnerToken", required = true , in = ParameterIn.HEADER)
	@Operation(summary = "获取当前登录用户的视图资源", description = "根据用户ID获取视图资源", tags = {"ossview"})
	public ResultMessage getViewResourcesByUserId(HttpServletRequest request){
		try {
			List<ViewResourceVo> viewListByUser = null;
			String token = (String)request.getHeader("ossInnerToken");
			if(StringUtils.isNotBlank(token)) {
				Long userId = TokenUtils.getIdFromToken(token, tokenKey);
				viewListByUser = viewService.getViewListByUser(userId);
			}
			return ResultMessage.success(viewListByUser);
		}catch (OssException e){
			logger.error(e.getMessage());
			return ResultMessage.error();
		}
	}

	@PostMapping("/create")
	@PrivilegeCheck(group = ApiGroup.SYSTEM,name = "创建视图资源",auth = true)
	@Parameter(name = "ossInnerToken", required = true , in = ParameterIn.HEADER)
	@Operation(summary = "创建视图资源", description = "创建视图资源", tags = {"ossview"})
	public ResultMessage createView(@RequestBody ViewVo vo){
		try {
			viewService.createOrUpdate(vo);
			return ResultMessage.success();
		}catch (OssException e){
			logger.error(e.getMessage());
			return ResultMessage.error();
		}
	}
}
